<template>
	<div class="content-box add-good-argument">
		<el-form ref="formRef" class="good-store-form" :model="form" :rules="rules" label-width="100px">
			<div class="el-form-sub-title">基本信息</div>

			<el-form-item label="角色名称" prop="roleName">
				<el-input v-model="form.roleName" placeholder="输入账号名称" :maxlength="30" />
			</el-form-item>
			<div class="el-form-sub-title">操作权限</div>
			<el-form-item label="角色权限">
				<role-table :table-data="roleData" @checkbox-change="tableCheckChange"></role-table>
			</el-form-item>
			<el-divider direction="vertical" />
			<el-form-item label-width="0" style="position: fixed; right: 55px; bottom: 50px; z-index: 3">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" v-debounce="onSubmit">保存</el-button>
				</div>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup lang="tsx">
import { FormRules, ElMessage } from 'element-plus';
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { fetchAddRole, fetchUpdateRole, fetchRoleDetail, fetchRoleData } from '/@/api/system';
import { verifyAccountName } from '/@/utils/toolsValidate';
import roleTable from './roleTable.vue';

const route = useRoute();
const router = useRouter();

const formRef = ref();
const form = ref<any>({
	roleName: '',
});

const editId = ref();
const roleData = ref<any[]>([]);

// 用户勾选的菜单
let menuIdList: Array<number> = [];
// 用户勾选的按钮
let buttonIdList: Array<number> = [];

// 表格里勾选事件回调
function tableCheckChange(backItem: any) {
	if (backItem.checked) {
		if (backItem.type == 'BUTTON' && !buttonIdList.includes(backItem.id)) {
			buttonIdList.push(backItem.id);
		} else if (backItem.type == 'MENU' && !menuIdList.includes(backItem.id)) {
			menuIdList.push(backItem.id);
		}
	} else {
		if (backItem.type == 'BUTTON') {
			buttonIdList.forEach((item, index) => {
				if (item === backItem.id) {
					buttonIdList.splice(index, 1);
				}
			});
		} else {
			menuIdList.forEach((item, index) => {
				if (item === backItem.id) {
					menuIdList.splice(index, 1);
				}
			});
		}
	}

	menuIdList = JSON.parse(JSON.stringify([...new Set(menuIdList)]));
	buttonIdList = JSON.parse(JSON.stringify([...new Set(buttonIdList)]));
}

const validateName = (rule: any, value: any, callback: any) => {
	if (!verifyAccountName(value)) {
		callback(new Error('账号名称仅支持中英文'));
	} else {
		callback();
	}
};

//校验规则
const rules = reactive<FormRules<any>>({
	roleName: [
		{ required: true, message: '输入角色名称', trigger: 'blur' },
		{
			validator: validateName,
			message: '请输入角色名称',
			trigger: 'blur',
		},
	],
});

const onSubmit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params = { ...form.value, menuIdList, buttonIdList };
			delete params.permissionList;
			const res = await (editId.value ? fetchUpdateRole : fetchAddRole)(params);
			if (res.code == 200) {
				ElMessage.success(editId.value ? '编辑角色成功' : '新增角色成功');
				back();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const back = () => {
	router.push('/system/role');
};

const initData = async () => {
	editId.value = route.params.id;
	if (editId.value) {
		const res: any = await fetchRoleDetail({ id: editId.value });
		if (res.code === 200) {
			form.value = res.data;
			const data = res.data.permissionList;
			roleData.value = data;
			const getChecked = (arr: any) => {
				arr.forEach((ele: any) => {
					if (ele.checked) {
						ele.type == 'BUTTON' ? buttonIdList.push(ele.id) : menuIdList.push(ele.id);
					}
					if (ele.children.length > 0) {
						getChecked(ele.children);
					}
				});
			};
			getChecked(data);
		}
	} else {
		const res = await fetchRoleData();
		if (res.code == 200) {
			roleData.value = res.data;
		}
	}
};

onMounted(() => {
	initData();
});
</script>

<style lang="scss">
.good-store-form {
	margin-bottom: 50px;
	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number,
		.el-cascader,
		.el-date-editor {
			width: 100%;
			max-width: 450px;
		}
	}
	.el-table {
		.el-form-item {
			width: 80%;
			max-width: 150px;
			margin: auto;
		}
	}
}
</style>
